package com.example.android

import android.text.TextUtils
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.Timer
import java.util.TimerTask

class MethodChannelMgr {
    companion object{
        private const val METHOD_CHANNEL = "com.example/method_channel"

        private var sMethodChannel: MethodChannel? = null
        fun init(dartExecutor:DartExecutor){
            sMethodChannel = MethodChannel(dartExecutor, METHOD_CHANNEL)
            sMethodChannel!!.setMethodCallHandler { call: MethodCall, result: MethodChannel.Result ->
                if (TextUtils.equals(call.method, "methodTest")) {
                    result.success("{\"para\":\"message from Android\"}")
                } else {
                    result.error(
                        "1",
                        "Illegal Argument Exception",
                        "Unsupported Method - " + call.method
                    )
                }
            }

        }

        fun callFlutter(method: String, arguments: Any?){
            sMethodChannel!!.invokeMethod(method, arguments)
        }

        fun testCallFlutter(){
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    GlobalScope.launch(Dispatchers.Main) {
                        sMethodChannel!!.invokeMethod("methodToFlutter", "Params from Android",
                            object : MethodChannel.Result {
                                override fun success(result: Any?) {
                                    println("testCallFlutter success receive: $result")
                                }

                                override fun error(
                                    errorCode: String,
                                    errorMessage: String?,
                                    errorDetails: Any?
                                ) {
                                    println("testCallFlutter error receive: $errorCode $errorMessage $errorDetails")
                                }

                                override fun notImplemented() {
                                    println("testCallFlutter receive: notImplemented")
                                }
                            })
                    }
                }
            }, (10 * 1000).toLong())
        }
    }
}